﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace xuptlibsearch
{
    public partial class Favorite : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/json";
            string id = Request.Form["ID"];
            string Password = Request.Form["Password"];
            if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(Password))
            {
                Response.Write("Param_Error");
                return;
            }
            try
            {
                GetHttp(id, Password);
            }
            catch
            {
                Response.Write("Server_Error");
                return;
            }
        }
        void GetHttp(string id, string password)
        {
            string param = string.Format("login_type=&barcode={0}&password={1}&_=", id, password);
            byte[] PostBin = Encoding.GetEncoding("GB2312").GetBytes(param);
            CookieContainer cookie = new CookieContainer();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://222.24.3.7:8080/opac_two/include/login_app.jsp");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = cookie;
            Stream stream = request.GetRequestStream();
            stream.Write(PostBin, 0, PostBin.Length);
            WebResponse response = request.GetResponse();
            stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"));
            string restr = reader.ReadToEnd();
            if (!restr.Contains("ok"))
            {
                Response.Write("Account_Error");
                return;
            }
            request = (HttpWebRequest)WebRequest.Create("http://222.24.3.7:8080/opac_two/reader/xunishujia.jsp");
            request.Method = "GET";
            request.CookieContainer = cookie;
            response = request.GetResponse();
            stream = response.GetResponseStream();
            reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"));
            restr = reader.ReadToEnd();
            if (restr.Contains("您没有虚拟书架信息"))
            {
                Response.Write("null");
                return;
            }
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(restr);
            List<FavoriteList> Data = new List<FavoriteList>();
            foreach (HtmlNode node in doc.DocumentNode.ChildNodes[1].ChildNodes[3].ChildNodes)
            {
                if (node.Name != "table")
                    continue;
                HtmlNodeCollection nodes = node.ChildNodes[3].ChildNodes[1].ChildNodes;
                
                FavoriteList Item = new FavoriteList();
                try
                {
                    foreach (HtmlNode n in nodes)
                    {

                        if (n.Name == "tr" && ((n.InnerHtml.Contains("题名")) || n.InnerHtml.Contains("ISBN") || (n.InnerHtml.Contains("出版社")) || (n.InnerHtml.Contains("责任者")) || (n.InnerHtml.Contains("分类号"))))
                        {
                            if (n.ChildNodes[1].InnerHtml.Contains("题名"))
                            {
                                string title = n.ChildNodes[3].ChildNodes[0].InnerText;
                                string sid = n.ChildNodes[3].ChildNodes[0].Attributes["href"].Value.Replace("../search2/s_detail.jsp?sid=", "");
                                Item.ID = sid.Replace("&nbsp;", "");
                                Item.Title = title.Replace("&nbsp;", "");
                                continue;
                            }
                            if (n.ChildNodes[0].InnerHtml.Contains("出版社"))
                            {
                                string pub = n.ChildNodes[1].InnerText;
                                Item.Pub = pub.Replace("&nbsp;", "");
                                continue;
                            }
                            if (n.ChildNodes[0].InnerHtml.Contains("ISBN"))
                            {
                                string isbn = n.ChildNodes[1].InnerText;
                                Item.ISBN = isbn.Replace("&nbsp;", "").Replace("-", "");
                                if (Item.ISBN.Contains(","))
                                {
                                    Item.ISBN = Item.ISBN.Remove(Item.ISBN.IndexOf(",")).Replace(",", "");
                                }
                                continue;
                            }
                            if (n.ChildNodes[0].InnerHtml.Contains("责任者"))
                            {
                                string author = n.ChildNodes[1].InnerText;
                                Item.Author = author.Replace("&nbsp;", "");
                                continue;
                            }
                            if (n.ChildNodes[0].InnerHtml.Contains("分类号"))
                            {
                                string sort = n.ChildNodes[1].InnerText;
                                Item.Sort = sort.Replace("&nbsp;", "");
                                break;
                            }
                        }

                    }
                }
                catch
                {
                    Response.Write("Server_Error");
                    return;
                }
                if (Item != null)
                {
                    try
                    {
                        DataSet.DataDataTable table = new DataSet.DataDataTable();
                        DataSetTableAdapters.DataTableAdapter adapter = new DataSetTableAdapters.DataTableAdapter();
                        table = adapter.GetDataByISBN(Item.ISBN);
                        string st;
                        //WebRequest re = WebRequest.Create("https://api.douban.com/v2/book/isbn/" + Item.ISBN);
                        if (table.Count == 0)
                        {
                            WebRequest re = WebRequest.Create("http://xiyoumobiledouban.duapp.com/?isbn=" + Item.ISBN);
                            WebResponse rp = re.GetResponse();
                            Stream sr = rp.GetResponseStream();
                            StreamReader read = new StreamReader(sr);
                            st = read.ReadToEnd();
                            adapter.InsertInfo(Item.ISBN, st);
                        }
                        else
                        {
                            st = table[0].Douban_JSON;
                        }
                        JObject data = JObject.Parse(st);
                        Item.Img = Convert.ToString(data["images"]["small"]);
                    }
                    catch { }
                    Data.Add(Item);
                }
            }
            JavaScriptSerializer json = new JavaScriptSerializer();
            Response.Write(json.Serialize(Data));
        }
    }
    public class FavoriteList
    {
        public string ID { get; set; }
        public string Title { get; set; }
        public string Pub { get; set; }
        public string Author { get; set; }
        public string Sort { get; set; }
        public string Img { get; set; }
        public string ISBN { get; set; }
    }
}